<template>
  <div>

    <div class="nc-background">
      <div class="nc-background-picture" ref="backgroundPicture">
      </div>

      <div class="nc-center">
        <div class="nc-index">
          <div class="floatSidebar">
            <SideBar
                ref="sideBarRef"
                :indexList="props.indexList"
                :noShowPlus="forbidData"
                :master-id="props.id"
                @scroll-to-section="scrollToSection"
                @add-title="addtitle"
                @remove-title="removetitle"
            >
            </SideBar>
          </div>
        </div>

        <div class="content">

          <DetailModeHeader ref="head" :id="props.id"></DetailModeHeader>

          <DetailModeMiddle ref="middle"  :id="props.id" :mode="mode" ></DetailModeMiddle>

          <DetailModeDown ref="down"  :id="props.id" :mode="mode"></DetailModeDown>

          <DetailModeContent ref="content" :id="props.id" :initData="props.indexList"
                             :sideBarRef="sideBarRef"
                             @scrollTo="scrollTo"
                             @update:editList="syncEditList"
                             @saveAllAndFresh="saveAllAndFresh"
                              ></DetailModeContent>
        </div>
      </div>
    </div>

  </div>
</template>
<script setup lang="ts">
import {reactive, ref, onBeforeMount, onMounted, computed, watch, type PropType} from "vue";
import 大背景 from '@/assets/images/preciousYou/大背景样例.jpg';
import SideBar from "./components/FloatSideBar.vue";
import DetailModeHeader from "@/views/novel/character/components/head/DetailModeHeader.vue";
import DetailModeMiddle from "@/views/novel/character/components/middle/DetailModeMiddle.vue";
import DetailModeDown from "@/views/novel/character/components/down/DetailModeDown.vue";
import DetailModeContent from "@/views/novel/character/components/content/DetailModeContent.vue";
import {
  batchUpdateDetailModeSideBarApi,
  createDetailModeSideBarApi,
  getDetailModeSideBarTreeApi, removeDetailModeSideBarApi
} from "@/api/modules/detailModel/detailModeSideBar";
import type {DetailModeSideBarForm} from "@/api/types/detailmodel/detailModeSideBar";
import {ElMessage} from "element-plus";

let backgroundPicture = ref();
let sideBarRef = ref();
let head = ref();
let down = ref();
let content = ref();
let mode = ref('read')

let props = defineProps({
  id: {
    type: Number,
    default: 2
  },
  indexList: {
    type: Array as PropType<{ id: string, title: string }[]>,  // 使用 PropType 来指定数组中每个元素的类型
    default: () => [
      { id: 'detail-head', title: '简介' },
      { id: 'detail-middle', title: '作品设定' },
      { id: 'detail-down', title: '角色定位' },
      { id: 'detail-content', title: '编辑区域' }
    ]
  }
});

let data = reactive({
  editList :  [] as {id:number,node:{},indexModel:string,title:string}[],
  trees: props.indexList as []
})

//必须在挂载后进行元素地位修改，不明原因无法在挂载前获取到元素，但挂载前用document的方法能获取【猜想：可能用element组件的才能在ts语法中挂载前使用】
onMounted(() => {
  backgroundPicture.value.style.backgroundImage = 'url(' + 大背景 + ')';
  backgroundPicture.value.style.backgroundSize = '100% 100%'; // 强制缩放图片以填充元素
})

let forbidData = ['detail-head', 'detail-middle', 'detail-down']

// 父组件维护多个模块的数据（可动态添加/删除）

/**
 * 滚动功能
 */
let scrollToSection = (data: any) => {
  if (typeof data.id === 'number' && !isNaN(data.id)) {
    // 貌似不生效
    // const numberId = eval(`editBox${data.id}`); // 动态获取对应的 ref
    // numberId.value.scrollIntoView({
    //   behavior: 'smooth',
    //   block: 'start',
    // });
    //方案二：通知子组件进行滚动
    //存在逻辑硬伤，无法通知调用哪个

    //方案三：去掉ref,使用Id  适合才是最好滴 ref貌似不支持动态
    const editBoxElement = document.getElementById(`editBox${data.id}`);
    if (editBoxElement) {
      editBoxElement.scrollIntoView({
        behavior: 'smooth',
        block: 'start',
      });
    }
    return
  }

  const levelOne = document.getElementById(`${data.id}`);
  if(levelOne){
    levelOne.scrollIntoView({
      behavior: 'smooth',
      block: 'start',
    });
  }
};


/**
 * 初始化数据
 */
let refreshData = ()=>{
  getDetailModeSideBarTreeApi({masterId: props.id}).then((res: any) => {
    //深拷贝
    let target = JSON.parse(JSON.stringify(props.indexList))
    target[props.indexList.length - 1].children = []
    target[props.indexList.length - 1].children.push(...res?.trees)
    //本地
    const map = res.contexts.reduce((map:any, context:any) => {
      map.set(context.id, context);
      return map;
    }, new Map<string, any>());
    setContextNode(res?.trees,map);//绑定内容区的node
    data.trees = target
    data.editList = res.contexts

    //赋值sidebar 不由watch控制
    sideBarRef.value.data = target

    //content组件
    content.value.syncEditList(data.editList)
  });
}
refreshData()


/**
 * 预期： 点击+号，自动滚到添加位置并同步input的信息
 *
 */
const addtitle = (node: any) => {
  console.log('获取到子组件的ID', node)
  if (node.level == 4) {
    console.log('只做绑值操作')
  }

  let nodeData = node.data

  //在执行了push之后就变成响应式对象了
  var radomNumber = Date.now();
  const newChild = {id: radomNumber, title: '', children: []}
  if (!nodeData.children) {
    nodeData.children = []
  }

  var find = data.editList.find((item: any) => item.id === nodeData.id);
  let index = 0;
  if (find !== undefined) {
    console.log(find);
    index = data.editList.indexOf(find);
    // 通过 ref 获取具体的组件实例
  } else {
    console.log("Item not found");
  }

  if (node.level == 1) {
    let test = "主标题" + sideBarRef.value.getChildNumber(2)
    newChild.title = test;
    data.editList.push({title: test, indexModel: 'titleOne', node: newChild, id: radomNumber});
    console.log('editList',data.editList)
    // editList.value.push({ value: test, indexModel:'titleOne',node :newChild,id:radomNumber })
    //需要存顺序
    let create :DetailModeSideBarForm = {
      id: radomNumber,
      label:newChild.title,
      ext1: props.id,
      ext: sideBarRef.value.getChildNumber(2),
      ext2: 1,
    }
    createDetailModeSideBarApi(create).then(res => {
      ElMessage.success('保存成功')
    })
    scrollToSection({id: "detail-content"})
  }

  if (node.level == 2) {
    let test = "副标题" + sideBarRef.value.getChildNumber(3)
    newChild.title = test;
    //对应长度为当前主标题下有多少孩子(递归获取)总长度
    data.editList.splice(index + ( getAllChildrenLength(nodeData) ?? 0) + 1, 0, {
      title: test,
      indexModel: 'titleTwo',
      node: newChild,
      id: radomNumber
    })


    //需要存顺序
    let create :DetailModeSideBarForm = {
      id: radomNumber,
      parentId: nodeData?.id,
      label:newChild.title,
      ext1: props.id,
      ext: getAllChildrenLength(nodeData) ?? 0,
      ext2: 2
    }
    createDetailModeSideBarApi(create).then(res => {
      ElMessage.success('保存成功')
    })
    scrollToSection({id: "detail-content"})
  }

  if (node.level == 3) {
    let test = '正文' + sideBarRef.value.getChildNumber(4)
    newChild.title = test;
    //对应长度为当前主标题下有多少正文的长度
    data.editList.splice(index + (nodeData.children?.length ?? 0) + 1, 0, {
      title: test,
      indexModel: 'context',
      node: newChild,
      id: radomNumber
    })

    //需要存顺序
    let create :DetailModeSideBarForm = {
      id: radomNumber,
      parentId: nodeData?.id,
      label:newChild.title,
      ext1: props.id,
      ext: getAllChildrenLength(nodeData) ?? 0,
      ext2: 3
    }
    createDetailModeSideBarApi(create).then(res => {
      ElMessage.success('保存成功')
    })
    // editList.value.push({value: test, indexModel: 'context', node: newChild, id: radomNumber})
  }

  //通知子组件展开所有节点
  //sideBarRef.value.resetChildTree(newChild);

  //同时滚动到对应位置(待定)
  //scrollToSection(newChild)

  nodeData.children.push(newChild)
};

/**
 * 移除
 */
let removetitle = (node: any) => {
  console.log('zsdfsadfw',node)
  console.log('zsdfsadfw',data.editList)
  let nodeData = node.data
  const index = data.editList.findIndex((item: any) => item.id === nodeData.id);
  if (index != undefined) {
    data.editList.splice(index, 1);
  }

  removeDetailModeSideBarApi({ ids: [nodeData?.id]}).then(res=>{
      ElMessage.success('删除成功')
  })
}
/**
 * 滚动到目的地
 */
let scrollTo = (obj: any) => {
  scrollToSection(obj)
}

//同步endList
let syncEditList = (list: any) => {
  data.editList = list;
}

//同步endList
let getAllChildrenLength = (node: any, initLength = 0): number => {
  console.log('开始计算所有儿子们的长度', node);
  if (!node) {
    return initLength;
  }
  if (node.children) {
    initLength += node.children.length;
    // 使用 reduce 来累加递归结果
    return node.children.reduce((acc:any, child:any) => {
      return getAllChildrenLength(child, acc);
    }, initLength);
  }

  return initLength;
}

let setContextNode = (trees:any, map:any)=>{
  trees.forEach((item: any)=>{
    let line = map.get(item.id)
    if (line!=null){
      line.node = item;
    }
    setContextNode(item?.children ?? [], map);
  })
}

let saveAllAndFresh = ()=>{
  console.log('触发了保存方法')
  batchUpdateDetailModeSideBarApi(data.editList).then(res => {
    ElMessage.success('保存成功')
    refreshData()
  });
}


//同步编辑模式到所有模块
watch(mode,(newValue)=>{
    head.value.updateModel(newValue)
})


</script>

<style scoped lang="scss">
@use 'index.scss';


</style>


